package com.tajiang.business.businesscount.store;

import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;
import com.tajiang.business.R;
import com.tajiang.business.businesscount.adapter.GoodsGovernAdapter;
import com.tajiang.business.common.activity.BaseActivity;
import com.tajiang.business.common.adapter.EmptyViewAdapter;
import com.tajiang.business.common.utils.BottomCallBackInterface;
import com.tajiang.business.common.utils.PostDataTools;
import com.tajiang.business.common.utils.Res;
import com.tajiang.business.common.utils.ToastUtils;
import com.tajiang.business.model.GoodsDetailInfo;
import com.tajiang.business.model.Order;
import com.tajiang.business.model.Pager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class GoodsGovernActivity extends BaseActivity implements OnRefreshListener, OnLoadMoreListener {

    @BindView(R.id.swipe_to_load_layout)
    SwipeToLoadLayout swipeToLoadLayout;

    @BindView(R.id.swipe_target)
    RecyclerView listView;

    @BindView(R.id.goods_govern_tv1)
    TextView tv1;

    @BindView(R.id.goods_govern_tv2)
    TextView tv2;

    @BindView(R.id.goods_govern_view_1)
    View view1;

    @BindView(R.id.goods_govern_view_2)
    View view2;

    @BindView(R.id.et_search_input)
    EditText edtSearch;

    @BindView(R.id.goods_govern_sel_all)
    CheckBox checkBox;

    @BindView(R.id.goods_govern_confirm_multy)
    Button btnMulty;

    private GoodsGovernAdapter mAdapter;
    private EmptyViewAdapter emptyViewAdapter;  //订单列表为空的时候显示空Adapter
    List<GoodsDetailInfo> dataList = new ArrayList<>();
    private int pageNumber = 1;//当前页
    private int goodsState = 1;//当前菜品所属状态 0:下架 1:上架
    private String goodsName = "";//搜索内容

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected void initTopBar() {
        setTitle("菜品管理");
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_goods_govern);

        edtSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                goodsName = charSequence.toString();
                onRefresh();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    @Override
    protected void initData() {

        swipeToLoadLayout.setOnRefreshListener(this);
        swipeToLoadLayout.setOnLoadMoreListener(this);
        swipeToLoadLayout.setLoadMoreEnabled(false);

        edtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    //TODO.....搜索....订单........
                    goodsName = edtSearch.getText().toString();
                    onRefresh();
                }
                return false;
            }
        });

        emptyViewAdapter = new EmptyViewAdapter(this, R.layout.layout_empty_order_view);
        mAdapter = new GoodsGovernAdapter(this, dataList, new BottomCallBackInterface.OnBottomClickListener() {

            @Override
            public void onBottomClick(View v, int position) {

                GoodsDetailInfo info = dataList.get(position);
                if(v.getId() == R.id.item_goods_govern_sel){

                    info.setChecked(!info.isChecked());
                    mAdapter.notifyDataSetChanged();
                }else if(v.getId() == R.id.item_goods_govern_btn){
                    handleData(info.getGoodsId());
                }
            }
        });

        listView.setLayoutManager(new LinearLayoutManager(this));
        listView.setItemAnimator(new DefaultItemAnimator());
        listView.setAdapter(emptyViewAdapter);

        onRefresh();
    }

    @Override
    public void onRefresh() {

        pageNumber = 1;
        PostDataTools.goods_list(this, goodsName, goodsState, pageNumber, swipeToLoadLayout, new PostDataTools.DataCallback() {

            @Override
            public void callback(boolean flag, String message, Object object) {

                Pager<GoodsDetailInfo> pager = (Pager<GoodsDetailInfo>) object;
                List<GoodsDetailInfo> newOrderList = pager.getList();

                dataList.clear();
                dataList.addAll(newOrderList);
                updateMyRecyclerView(dataList);

                if (newOrderList.size() >= Order.PAGE_SIZE){
                    pageNumber = 2;
                    swipeToLoadLayout.setLoadMoreEnabled(true);
                }
            }
        });
    }

    @Override
    public void onLoadMore() {

        PostDataTools.goods_list(this, goodsName, goodsState, pageNumber, swipeToLoadLayout, new PostDataTools.DataCallback() {

            @Override
            public void callback(boolean flag, String message, Object object) {

                Pager<GoodsDetailInfo> pager = (Pager<GoodsDetailInfo>) object;
                List<GoodsDetailInfo> newOrderList = pager.getList();

                dataList.addAll(newOrderList);
                updateMyRecyclerView(dataList);

                if (newOrderList.size() >= Order.PAGE_SIZE){
                    ++pageNumber;
                    swipeToLoadLayout.setLoadMoreEnabled(true);
                }else{
                    swipeToLoadLayout.setLoadMoreEnabled(false);
                }
            }
        });
    }

    /**
     * 对订单的一系列操作之后更新当前订单数据
     *
     * @param newOrderList
     */
    private void updateMyRecyclerView(List<GoodsDetailInfo> newOrderList) {

        try {
            if (newOrderList != null) {
                if (newOrderList.size() < 1) {
                    listView.setAdapter(emptyViewAdapter);
                } else {
                    listView.setAdapter(mAdapter);
                }

                mAdapter.notifyDataSetChanged();
            }
        } catch (Exception ex) {
            Log.d("【updateMyRecyclerView】", "异常：" + ex.getMessage());
        }
    }

    @OnClick(R.id.goods_govern_layout_1)
    public void goods_ok(){

        goodsState = 1;
        tv1.setTextColor(Res.getColor(R.color.text_black));
        tv2.setTextColor(Res.getColor(R.color.text_black_1));
        view1.setBackgroundColor(Res.getColor(R.color.main_color));
        view2.setBackgroundColor(Res.getColor(R.color.gray));
        btnMulty.setText("批量下架");

        onRefresh();
    }

    @OnClick(R.id.goods_govern_layout_2)
    public void goods_no(){

        goodsState = 0;
        tv2.setTextColor(Res.getColor(R.color.text_black));
        tv1.setTextColor(Res.getColor(R.color.text_black_1));
        view2.setBackgroundColor(Res.getColor(R.color.main_color));
        view1.setBackgroundColor(Res.getColor(R.color.gray));
        btnMulty.setText("批量上架");

        onRefresh();
    }

    @OnClick(R.id.goods_govern_sel_all)
    public void sel_all() {

        boolean flag = checkBox.isChecked();

        int len = dataList.size();
        for(int i=0; i<len; i++){

            GoodsDetailInfo info = dataList.get(i);
            info.setChecked(flag);
        }

        mAdapter.notifyDataSetChanged();
    }

    @OnClick(R.id.goods_govern_confirm_multy)
    public void multy_confirm() {

        StringBuffer sb = new StringBuffer();
        int len = dataList.size();
        for(int i=0; i<len; i++){

            GoodsDetailInfo info = dataList.get(i);
            if(info.isChecked()){

                if(TextUtils.isEmpty(sb.toString())){
                    sb.append(info.getGoodsId());
                }else{
                    sb.append(",").append(info.getGoodsId());
                }
            }
        }

        if(TextUtils.isEmpty(sb.toString())){
            ToastUtils.showShort("请至少选择一条数据");
            return;
        }

        handleData(sb.toString());
    }

    public void handleData(final String goodsIds){

        PostDataTools.goods_state(this, goodsIds, goodsState == 1 ? 0 : 1, new PostDataTools.DataCallback() {

            @Override
            public void callback(boolean flag, String message, Object object) {

                for(int i=0; i<dataList.size(); i++){

                    GoodsDetailInfo info = dataList.get(i);
                    if(goodsIds.contains(info.getGoodsId())){
                        dataList.remove(i);
                        --i;
                    }
                }

                checkBox.setChecked(false);
                mAdapter.notifyDataSetChanged();
            }
        });
    }
}
